﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Model.Common.Product.Entity;
using DiLe.Mes.Model.Common.System.Entity;

namespace DiLe.Mes.Cloud.Controllers.SystemManage {
    /// <summary>
    /// 
    /// </summary>
    public class SystemExjosnHandler {
        private readonly OrganizationClient _organizationClient;
        private readonly SystemClient _systemClient;
        private readonly ProductClient _productClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public SystemExjosnHandler(OrganizationClient organizationClient, SystemClient systemClient, ProductClient productClient) {
            _organizationClient = organizationClient;
            _systemClient = systemClient;
            _productClient = productClient;
        }
        /// <summary>
        /// 填充设备存放位置的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillPositionExjosn(List<PositionEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            //部门
            var factoryIds = dataList.Where(x => x.Factory != null).Select(p => p.Factory!.Value).Distinct().ToList();
            var factoryList = await _organizationClient.GetOrganizationListAsync(factoryIds);
            //负责人
            var customerIds = dataList.Where(x => x.Customer != null).Select(p => p.Customer!.Value).Distinct().ToList();
            var customerList = await _organizationClient.GetUserListByIdAsync(customerIds);

            foreach (var item in dataList) {
                var factory = factoryList?.FirstOrDefault(p => p.Id == item.Factory);
                item.ExtJson.Add("FactoryName", factory?.Name);
                var customer = customerList?.FirstOrDefault(p => p.Id == item.Customer);
                item.ExtJson.Add("CustomerName", customer?.Name);
            }
        }

        /// <summary>
        /// 填充产品信息的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillProductInfoExjosn(List<ProductInfoEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            //单位
            var unitIds = dataList.Select(p => p.UnitId).Distinct().ToList();
            var unitList = await _systemClient.GetMeasureUnitListAsync(p => unitIds.Contains(p.Id));
            //类型
            var categoryIds = dataList.Select(p => p.CategoryId).Distinct().ToList();
            var categoryList = await _productClient.GetProductTypeListAsync(p => categoryIds.Contains(p.Id));

            foreach (var item in dataList) {
                var unit = unitList?.FirstOrDefault(p => p.Id == item.UnitId);
                item.ExtJson.Add("UnitName", unit?.Name);
                var category = categoryList?.FirstOrDefault(p => p.Id == item.CategoryId);
                item.ExtJson.Add("CategoryName", category?.Name);
            }
        }
    }
}
